package com.tinckay.common.filter;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yuanjie
 */
@Component
public class SimpleCorsFilter implements Filter {

    private FilterConfig config = null;
    public static final String REFERER = "Referer";

    @Override
    public void init(FilterConfig config) {
        this.config = config;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        String origin = request.getHeader("Origin");
        String method = request.getMethod();
        if (origin == null) {
            origin = request.getHeader(REFERER);
        }
        // 允许客户端携带跨域cookie，此时origin值不能为“*”，只能为指定单一域名
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
        response.setHeader("Access-Control-Max-Age", "86400");
        response.addHeader("Access-Control-Allow-Headers", "origin, no-cache, x-requested-with, if-modified-since, pragma, last-modified, cache-control, expires, content-type, x-e4m-with");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Expose-Headers", "*");
        //Shiro获取不到认证token，options请求直接返回
        if (RequestMethod.OPTIONS.name().equals(method)) {
            response.setStatus(HttpStatus.OK.value());
            return;
        }
        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {
    }
}
